import React, { useEffect, useMemo, useRef, useState } from 'react';
import { List, message, Skeleton } from 'antd';
import MessageItem from './MessageItem';
import { SvgIcon } from '@/components/icon';
import { ChatItem } from '@/types/chat';
import { useThrottleFn, useUpdateLayoutEffect } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useChatRecordLoading } from '@/store/configStore';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { AppType } from '@/common/app/constants';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useParams } from '@/router/hooks';

interface ChatListProps {
  messages: ChatItem[];
  isMessageSend?: boolean;
  deleteMessage?: (index: number) => void;
  reFreshAnswer?: (index: number) => void;
  handleSend?: (message: string) => void;
  isChat?: boolean;
  guessQuestions?: { id: string; content: string }[];
  onQuestionClick?: (question: string) => void;
  workflowDebug?: boolean;
}

const ChatList = ({
  messages,
  isMessageSend,
  deleteMessage,
  handleSend,
  reFreshAnswer,
  isChat = true,
  guessQuestions,
  onQuestionClick,
  workflowDebug = false,
}: ChatListProps) => {
  const chatListRef = useRef<HTMLDivElement>(null);
  const [hideItem, setHideItem] = useState(false);
  const [isUserScrolling, setIsUserScrolling] = useState(false);
  const { isPc } = useWindowWidth();
  const chatRecordLoading = useChatRecordLoading();
  const [thinkState, setThinkState] = useState<1 | 2>(1);
  // const [starState, setStarState] = useState<1 | 2 | 3 | 4>(1);

  const { appId = '' } = useParams() as { appId: string };


  const {
    appLogo: appLogoStore,
    appName: appNameStore,
    isInOrchestrationPage,
  } = useOrchestrationStore();

  useEffect(() => {
    const timer = setInterval(() => {
      setThinkState((prev) => (prev === 1 ? 2 : 1));
      // setStarState((prev) => (prev === 3 ? 1 : (prev + 1) as typeof prev));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  const { run } = useThrottleFn(
    () => {
      if (!isUserScrolling && chatListRef.current) {
        chatListRef.current.scrollTop = chatListRef.current.scrollHeight;
      }
    },
    { wait: 500 },
  );

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      if (chatListRef.current) {
        const currentScrollTop = chatListRef.current.scrollTop;
        const previousScrollTop = chatListRef.current.getAttribute('data-previous-scroll-top');
        // message.info(Number(previousScrollTop)?.toString() + '-' + (currentScrollTop + 50)?.toString() + '-' + (currentScrollTop + chatListRef.current.clientHeight)?.toString() + '-' +  ((chatListRef.current.scrollHeight || 0) - 150)?.toString())
        // console.log(previousScrollTop, currentScrollTop, currentScrollTop + chatListRef.current.clientHeight, chatListRef.current.scrollHeight - 150)

        if (previousScrollTop && currentScrollTop > 50 && Number(previousScrollTop) > (currentScrollTop + 50)) {
          setIsUserScrolling(true);
        } else {
          const atBottom =
            currentScrollTop + chatListRef.current.clientHeight >=
            chatListRef.current.scrollHeight - 150;
          setIsUserScrolling(!atBottom);
        }

        chatListRef.current.setAttribute('data-previous-scroll-top', currentScrollTop.toString());
      }
    };

    const chatListElement = chatListRef.current;

    if (chatListElement) {
      chatListElement.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (chatListElement) {
        chatListElement.removeEventListener('scroll', handleScroll);
        chatListElement.setAttribute('data-previous-scroll-top', '0');
      }
    };
  }, []);

  useEffect(() => {
    // console.log('触发几次', isMessageSend);

    if (isMessageSend == true) {
      setIsUserScrolling(false);
    }
    // run();
    setHideItem(isMessageSend ?? false);
  }, [isMessageSend]);
  const chatList = document.querySelector('.chat-list');


  useUpdateLayoutEffect(() => {
    // message.info('aa-'+ messageInput?.clientHeight + '-' + window.innerHeight + '-' + chatList?.clientHeight)
    if (!isUserScrolling) {
      run();
    }
  }, [messages]);

  // 最后一个消息大小变化后触发滚动到最后
  const scrollToBottom = () => {
    run();
  };

  const messageInput = document.querySelector('.qa-message-send-input');
  const messageInputHeight = useMemo(() => {
    if (!isPc) {
      if (chatList?.clientHeight && window.innerHeight - chatList?.clientHeight < 50) {
        return (messageInput?.clientHeight ?? 0) + 120;
      }
      return (messageInput?.clientHeight ?? 0) + 20;
    }
    return undefined;
  }, [messageInput?.clientHeight, isPc, chatList?.clientHeight]);

  return (
    <div
      ref={chatListRef}
      className={`chat-list hide-scrollbar flex-1 overflow-y-auto px-2 ${isPc && 'flex justify-center py-4'}`}
      style={{ 
        paddingBottom: messageInputHeight,
      }}
    >
      {/* background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, #FFFFFF 100%); */}

      {/* {messages.length === 0 && (!isChat || chatRecordLoading) && (
        <>
          <div className="flex justify-end" style={{ padding: '20px 0' }}>
            <Skeleton.Input active={true} block={false} />
          </div>
          <div className="flex justify-start">
            <Skeleton active paragraph={{ rows: 5 }} />
          </div>
          <div className="flex justify-end" style={{ padding: '20px 0' }}>
            <Skeleton.Input active={true} block={false} />
          </div>
          <div className="flex justify-start">
            <Skeleton active paragraph={{ rows: 5 }} />
          </div>
        </>
      )} */}
      {messages.length > 0 && (
        <List
          className={`${isPc ? 'w-[800px]' : ''}`}
          itemLayout="horizontal"
          split={false}
          dataSource={messages}
          renderItem={(item, index) => (
            <List.Item>
              <div
                className={`flex w-full flex-col ${item.isUser ? 'justify-end' : 'justify-start'}`}
              >
                {!item.isUser && (
                  <div className="flex items-center">
                    {item?.appLogo && (
                      <>
                        <AvatarDisplay
                          src={isInOrchestrationPage && appId == item?.appId ? appLogoStore : item?.appLogo as string}
                          size={24}
                          className="h-[24px] w-[24px] flex-shrink-0"
                        />
                        <div className="flex-shrink-0 pl-2 text-[14px] font-font-weight-600 text-text-5">
                          {isInOrchestrationPage && appId == item?.appId ? appNameStore : item?.appName}
                        </div>
                      </>
                    )}
                    {/* <div className="ml-2 font-bold">
                      {item.loading &&
                        (item?.loadingText ? (
                          <div id="answer">
                            <SvgIcon icon="ic_rj_loading" color="var(--brand-color)" size="14" />
                            <span style={{ color: 'var(--brand-color)', paddingLeft: '10px' }}>
                              AI回答中...
                            </span>
                          </div>
                        ) : (
                          <div id="think">
                            <SvgIcon icon="ic_rj_loading" color="var(--brand-color)" size="14" />
                            <span style={{ color: 'var(--brand-color)', paddingLeft: '10px' }}>
                              AI思考中...
                            </span>
                          </div>
                        ))}
                    </div> */}
                    <div className="ml-2 font-bold" style={{ height: '14px', display: 'flex', alignItems: 'center' }}>
                      {item.loading && (
                        <div className="flex items-center" style={{ overflow: 'visible' }}>
                          {/* 思考icon */}
                          <div
                            style={{
                              width: '50px',
                              height: '50px',
                              marginRight: '8px',
                              overflow: 'visible',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              position: 'relative',
                            }}
                          >
                            {[1, 2].map((state) => (
                              <SvgIcon
                                key={state}
                                icon={`ai-chat-think${state}`}
                                color="var(--brand-color)"
                                style={{
                                  width: '50px',
                                  height: '50px',
                                  position: 'absolute',
                                  opacity: thinkState === state ? 1 : 0,
                                  transition: 'opacity 500ms linear 1ms',
                                }}
                              />
                            ))}
                          </div>
                          {/* 星星旋转图标 */}
                          <div className="flex justify-center items-center" style={{ width: '14px', height: '14px', position: 'relative' }}>
                            <SvgIcon
                              icon="ai-chat-star1"
                              color="var(--brand-color)"
                              size="14"
                              style={{
                                animation: 'star-spin 1.2s linear infinite',
                                width: '14px',
                                height: '14px',
                              }}
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}
                <MessageItem
                  key={index}
                  item={item}
                  index={index}
                  isMessageSend={isMessageSend}
                  hideItem={hideItem}
                  handleSend={handleSend ?? (() => {})}
                  isLastOne={index === messages.length - 1}
                  scrollToBottom={scrollToBottom}
                  deleteMessage={deleteMessage}
                  reFreshAnswer={reFreshAnswer}
                  guessQuestions={guessQuestions}
                  onQuestionClick={onQuestionClick}
                  workflowDebug={workflowDebug}
                ></MessageItem>
              </div>
            </List.Item>
          )}
        />
      )}
    </div>
  );
};

export default React.memo(ChatList);
